<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="教育集团名称" prop="edgroup_id">
        <el-select
          v-model="queryParams.edgroup_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeQueryEdgroup"
        >
          <el-option
            v-for="item in EdgroupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="学校名称"
        prop="school_id"
        v-if="queryParams.edgroup_id"
      >
        <el-select
          v-model="queryParams.school_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeQuerySchool"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="班级名称"
        prop="class_id"
        v-if="queryParams.school_id"
      >
        <el-select
          v-model="queryParams.class_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
        >
          <el-option
            v-for="item in classList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="网关MAC地址" prop="mac">
        <el-input
          v-model="queryParams.mac"
          placeholder="请输入网关MAC地址"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网关固件版本" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入网关固件版本"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
               v-model="dateRange"
               value-format="YYYY-MM-DD"
               type="daterange"
               range-separator="-"
               start-placeholder="开始日期"
               end-placeholder="结束日期"
            ></el-date-picker>
         </el-form-item> -->
      <el-form-item label="分布位置" prop="site">
        <el-select
            v-model="queryParams.site"
            placeholder="请选择分布位置"
            style="width: 260px"
            clearable
          >
            <el-option
              v-for="dict in gw_site_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        <!-- <el-select
          v-model="queryParams.outdoor"
          placeholder="是否室外"
          style="width: 120px"
          clearable 
          @change="handleQuery"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleOnline"
          >未入网网关</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
          >新增网关</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Download"
               @click="handleExport"
               v-hasPermi="['system:post:export']"
            >导出</el-button>
         </el-col> -->
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="gatewayLists"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="序号" width="60" type="index" align="center" /> -->
      <el-table-column label="序号" width="55" type="index" align="center" fixed="left">
        <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="网关编号" width="290" align="center" prop="id" /> -->
      <el-table-column
        label="网关MAC地址"
        width="150"
        align="center"
        prop="mac"
        fixed="left"
      />
      <el-table-column label="入网方式" align="center" prop="ifac">
        <template #default="scope">
          <el-tag v-if="scope.row?.ifac=='eth'" type="primary">ETH</el-tag>
          <el-tag v-else-if="scope.row?.ifac=='sta'" type="success">WIFI</el-tag>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="IP/SSID/AUTHMODE" align="center" prop="sta_ip" min-width="190">
        <template #default="scope">
          <el-tag v-if="scope.row?.sta_ip" :type="scope.row?.sta_ip?'success':'danger'">
            {{ `WIFI：${scope.row?.sta_ip || '-'} ${scope.row?.ssid || '-'} ${scope.row?.authmode || '-'}`}}
          </el-tag>
          <el-tag v-if="scope.row?.eth_ip" :type="scope.row?.eth_ip?'primary':'danger'">
            {{ `ETH：${scope.row?.eth_ip || '-'} ${scope.row?.ssid || '-'} ${scope.row?.authmode || '-'}`}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="ETH / WIFI / 蓝牙 / 热点" min-width="190" align="center" prop="class">
        <template #default="scope">
          <el-tag v-if="scope.row?.eth_mac" type="primary">
            ETH：{{ scope.row?.eth_mac }}
          </el-tag>
          <span></span>
          <el-tag v-if="scope.row?.wifi_sta_mac" type="success">
            WIFI： {{ scope.row?.wifi_sta_mac }}
          </el-tag>
          <el-tag v-if="scope.row?.bt_mac" type="warning">
            蓝牙： {{ scope.row?.bt_mac }}
          </el-tag>
          <el-tag v-if="scope.row?.wifi_ap_mac" type="info">
            热点： {{ scope.row?.wifi_ap_mac }}
          </el-tag>
          <!-- {{ `${scope.row?.eth_mac || '--'} / ${scope.row?.wifi_sta_mac || '--'} /${scope.row?.bt_mac || '--'} /${scope.row?.wifi_ap_mac || '--'} `}} -->
        </template>
      </el-table-column>
      <el-table-column label="在线时长(s)" align="center" prop="online_time" min-width="190">
        <template #default="scope">
          <el-tag v-if="scope.row?.online_time">
            {{scope.row?.online_time}} 
            
          </el-tag>
          <div v-if="scope.row?.online_time">
            ( <span style="color: #67c23a;">{{ formatOnlineTime(scope.row?.online_time, true) }}</span> )
          </div>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column label="温度" align="center" prop="gw_temperature">
        <template #default="scope">
          <b :style="{ color: getTemperatureColor(scope.row?.gw_temperature || 0) }">
            {{ formatTemperature(scope.row.gw_temperature)}}
          </b>
        </template>
      </el-table-column>
      <!-- <el-table-column label="CPU情况" align="center" prop="cpu1" min-width="150">
        <template #default="scope">
          <el-tag  v-if="scope.row?.cpu1" :type="100-Number(scope.row?.cpu1) > 50?'danger':100-Number(scope.row?.cpu1) >= 30?'warning':'success'">
            cpu1: {{ 100-Number(scope.row?.cpu1) || '*'}} %
          </el-tag>
          <el-tag v-if="scope.row?.cpu2" :type="100-Number(scope.row?.cpu2) > 50?'danger':100-Number(scope.row?.cpu2) >= 30?'warning':'success'">
            cpu2: {{ 100-Number(scope.row?.cpu2) || '*'}} %
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="内存使用" align="center" prop="sram" min-width="150">
        <template #default="scope">
          <el-tooltip :content="`sram: ${scope.row?.sram || '-'}`" placement="top">
            <el-tag
              v-if="scope.row?.sram"
              :type="Number(calcPercent(scope.row.sram)) > 50 ? 'danger' : Number(calcPercent(scope.row.sram)) >= 30 ? 'warning' : 'success'"
            >
              sram: {{ calcPercent(scope.row.sram) }}%
            </el-tag>
          </el-tooltip>
          <el-tooltip :content="`psram: ${scope.row?.psram || '-'}`" placement="top">
            <el-tag
              v-if="scope.row?.psram"
              :type="Number(calcPercent(scope.row.psram)) > 50 ? 'danger' : Number(calcPercent(scope.row.psram)) >= 30 ? 'warning' : 'success'"
            >
              psram: {{ calcPercent(scope.row.psram) }}%
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="上次离线原因" align="center" prop="reset_reason" min-width="120">
        <template #default="scope">
          <dict-tag v-if="scope.row?.reset_reason" :options="gw_reset_reason" :value="scope.row?.reset_reason" />
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="学校 / 班级" align="center" prop="class" min-width="120">
        <template #default="scope">
          <el-tag v-if="scope.row?.class?.school?.name" type="primary">
            {{ scope.row?.class?.school?.name }}
          </el-tag>
          <el-tag v-if="scope.row?.class?.name" type="warning">
            {{ scope.row?.class?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订阅主题" align="center" prop="topic" />
      <el-table-column label="固件版本" align="center" prop="version">
        <template #default="scope">
          <el-tag type="primary">
            BIN: {{ scope.row?.version_bin || '--' }}
          </el-tag>
          <el-tag type="success">
            FS: {{ scope.row?.version_fs || '--'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="场景" align="center" prop="scene" />
      <el-table-column label="分布位置" align="center" prop="site" >
        <template #default="scope">
          <dict-tag v-if="scope.row?.site" :options="gw_site_type" :value="scope.row?.site" />
          <span v-else>--</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="是否室外"
        width="80"
        align="center"
        prop="outdoor"
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.outdoor" type="primary">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column
        label="图片"
        show-overflow-tooltip
        align="center"
        prop="photo"
        min-width="140"
      >
        <template #default="scope">
          <div style="z-index: 10000">
            <el-image
              v-if="scope.row.photo"
              style="width: 100px; height: 100px"
              :src="scope.row.photo"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              hide-on-click-modal
              preview-teleported
              :preview-src-list="[scope.row.photo]"
              show-progress
              :initial-index="0"
              fit="cover"
            />
            <span v-else>暂无图片</span>
          </div>
        </template>
      </el-table-column>
      <!-- 是否在线 -->
      <el-table-column
        label="在线时间"
        align="center"
        prop="time"
        min-width="190"
        fixed="right"
        sortable
      >
        <template #default="scope">
          <!-- {{ scope.row.time ? formartIOSDate(scope.row.time) : "--" }} -->
          <span v-if="scope.row.time">
            {{scope.row.time || '--'}}
          </span>
          <div v-if="scope.row.time">
            ( <span style="color: #67c23a;">{{ formatOnlineTime(scope.row.time) }}</span> )
          </div>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="reg_time"
        width="180"
        fixed="right"
        sortable
      />
      <el-table-column
        label="操作"
        min-width="180"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="connection"
            @click="handleWristband(scope.row)"
            >绑定手环</el-button
          > -->
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
<!-- 为 el-dropdown 添加样式来移除蓝色边框，通常蓝色边框是聚焦时的样式 -->
          <el-dropdown style="--el-dropdown-menu-item-hover-bg-color: var(--el-color-primary-light-9);vertical-align: middle;">
            <el-button link type="primary">
              <el-icon><DArrowRight /></el-icon> 更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'red')" style="color: #f56c6c;">红灯</el-dropdown-item>
                <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'green')" style="color: #67c23a;">绿灯</el-dropdown-item>
                <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'blue')" style="color: #409EFF;">蓝灯</el-dropdown-item>
                <el-dropdown-item icon="Bell" @click="() => handleOperate(scope.row, 'buzzer')" style="color: #e6a23c;">蜂鸣</el-dropdown-item>
                <el-dropdown-item icon="ChromeFilled" @click="() => handleOperate(scope.row, 'telnet')">终端</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改网关对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="firmwareRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="网关MAC地址">
          <el-input v-model="form.mac" disabled />
        </el-form-item>
        <el-form-item label="学校" prop="class.school.id">
          <el-select
            v-model="form.class.school.id"
            allow-create
            filterable
            placeholder="请选择学校"
            @change="changeSchool(form.class.school.id)"
          >
            <el-option
              v-for="school in schoolList"
              :key="school.value"
              :label="school.label"
              :value="school.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.outdoor!=true" label="班级" prop="class.id">
          <el-select
            v-if="classList.length > 0"
            v-model="form.class.id"
            allow-create
            filterable
            placeholder="请选择班级"
          >
            <el-option
              v-for="classVal in classList"
              :key="classVal.value"
              :label="classVal.label"
              :value="classVal.value"
            ></el-option>
          </el-select>
          <el-input v-else disabled placeholder="该学校暂未分配班级" />
        </el-form-item>
        <el-form-item label="订阅主题" prop="topic">
          <el-input v-model="form.topic" placeholder="请输入订阅主题" />
        </el-form-item>
        <el-form-item label="固件版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入固件版本" />
        </el-form-item>
        <el-form-item label="场景" prop="scene">
          <el-input v-model="form.scene" placeholder="请输入场景" />
        </el-form-item>
        <el-form-item label="分布位置" prop="site">
          <el-select
            v-model="form.site"
            placeholder="请选择分布位置"
            style="width: 260px"
          >
            <el-option
              v-for="dict in gw_site_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否室外" prop="outdoor">
          <el-radio-group v-model="form.outdoor" @change="changeOutdoor">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="图片" prop="photo">
          <ImageUpload
            :limit="6"
            list-type="picture-card"
            v-model="form.photo"
            :on-success="handleUploadSuccess"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 配置手环 -->
    <!-- 默认 RSSI>-70 -->
    <el-dialog
      :title="titleWristband"
      v-model="openWristband"
      width="800px"
      append-to-body
    >
      <el-table
        ref="tableRef"
        v-loading="loadingWrisband"
        :data="wristbandList"
        @selection-change="handleSelectionWristbandChange"
        style="width: 100%"
        height="auto"
        size="small"
        row-key="mac"
        :reserve-selection="true"
      >
        <el-table-column fixed type="selection" width="55" align="center" />
        <el-table-column
          fixed
          label="序号"
          width="60"
          type="index"
          align="center"
        />
        <el-table-column label="手环名称" align="center" prop="wristband">
          <template #default="scope">
            {{ scope.row.wristband.fw_name || "--" }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="手环网关编号" width="320" align="center" prop="id" /> -->
        <el-table-column
          label="手环MAC地址"
          width="130"
          align="center"
          prop="mac"
        />
        <el-table-column label="手环固件版本" align="center" prop="fw_version">
          <template #default="scope">
            {{ scope.row.wristband.fw_version || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="信号值" align="center" prop="rssi" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="time"
          width="180"
          sortable
        >
          <template #default="scope">
            {{ scope.row.time ? formartIOSDate(scope.row.time) : "--" }}
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParamsWrisband.pageNum"
        v-model:limit="queryParamsWrisband.pageSize"
        @pagination="getWristbandLists"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitWristbandForm"
            :disabled="idsWrisband.length <= 0"
            >关联</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 为入网网关 -->
  <!-- <el-dialog title="网关入网" v-model="openOnline" width="800px" append-to-body>

  </el-dialog> -->
</template>

<script setup name="Post">
import { getCurrentInstance } from 'vue'

import {
  getGatewayList,
  getWristbandAdvById,
  createGatewayWristband,
  updateGagewayByMac,
} from "@/api/system/firmware/gateway";
import { getClassList, getClassGwControlLed } from "@/api/system/school/class";
import { getSchoolList } from "@/api/system/school/school";
import { getEdgroupList } from "@/api/system/school/edgroup";
import { getGatewayByMac, deleteGwByMac } from "@/api/system/firmware/gateway";
import { reactive } from "vue";
import { formartIOSDate, formatDate, formatSeconds } from "@/utils/dateFormart";
const { proxy } = getCurrentInstance();
const { gw_site_type, gw_reset_reason } = proxy.useDict("gw_site_type","gw_reset_reason");
console.log("gw_site_type", gw_site_type);
const EdgroupList = ref();
const schoolList = ref([]);
const classList = ref([]);
const gatewayLists = ref([]);
const open = ref(false);
const openWristband = ref(false);
const wristbandList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const titleWristband = ref("");
const dateRange = ref([]);
const tableRef = ref(null); // el-table 的引用
const limit = ref(1);
const props = defineProps({
  edgroup_id: {
    type: [String, Number],
    required: false, // 因为可能不传入，设为非必填
    default: undefined
  },
  school_id: {
    type: [String, Number],
    required: false, // 因为可能不传入，设为非必填
    default: undefined
  },
  class_id: {
    type: [String, Number],
    required: false, // 因为可能不传入，设为非必填
    default: undefined
  }
});



// 定义 formatOnlineTime 方法
const formatOnlineTime = (time, status) => {
  if (!time) {
    return ' -- ';
  }
  const countTime = status ? formatSeconds(time) : formatDate(time);
  return countTime || ' -- ';
};

const getTemperatureColor = (temperature) => {
  if (temperature && temperature > 60) {
    return '#F56C6C';
  } else if (temperature && temperature >= 50) {
    return '#E6A23C';
  } else if (temperature && temperature >= -10) {
    return '#67c23a';
  } else {
    return '#999999'; // 默认颜色
  }
};
function calcPercent(val) {
  if (!val || typeof val !== 'string' || !val.includes('/')) return '--';
  const [used, total] = val.split('/').map(v => Number(v.trim()));
  if (!used || !total) return '--';
  return ((used / total) * 100).toFixed(1);
}
function formatTemperature(val) {
  if(!val){
    return '--'
  }
  const str = String(val);
  const idx = str.indexOf('.');
  if (idx === -1) return str;
  return str.substring(0, idx + 2); // 保留到小数点后一位，不四舍五入
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mac: undefined,
    version: undefined,
    // outdoor: undefined,
    site: undefined,
  },
  rules: {
    "class.id": [{ required: true, message: "班级不能为空", trigger: "blur" }],
    "class.school.id": [
      { required: true, message: "学校不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

function rawChange(val) {
  if (!val) {
  }
}

const wrisbandData = reactive({
  formWrisband: {},
  idsWrisband: [],
  loadingWrisband: false,
  queryParamsWrisband: {
    pageNum: 1,
    pageSize: 10,
    mac: undefined,
  },
});

// const gatewayOline = reactive({
//   openOnline: false,
// })

const { formWrisband, idsWrisband, loadingWrisband, queryParamsWrisband } =
  toRefs(wrisbandData);
function changeSchool(e) {
  form.value.class.school.name = schoolList.value.find(
    (item) => item.value == e
  ).label;
  form.value.class.school.photo = schoolList.value.find(
    (item) => item.value == e
  ).photo;
  classList.value = [];
  let params = {
    school_id: e,
  };
  getClassList(params).then((res) => {
    if (res.data.data.length > 0) {
      classList.value = res.data.data.map((item) => {
        return {
          label: item.name,
          value: item.id,
          photo: item.photo,
        };
      });
    } else {
      classList.value = [];
      form.value.class.id = null;
      form.value.class.name = undefined;
      form.value.class.photo = undefined;
    }
  });
}
/** 查询网关列表 */
function getList() {
  loading.value = true;
  getGatewayList(queryParams.value).then((response) => {
    console.log("网关列表", response.data.data);
    gatewayLists.value = response.data.data;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 查询手环列表 */
function getWristbandLists() {
  loadingWrisband.value = true;
  // 要绑定
  getWristbandAdvById(queryParamsWrisband.value).then((response) => {
    // console.log("手环列表", response.data);
    wristbandList.value = response.data.value;
    if (response.data.connected) {
      idsWrisband.value = response.data.connected.split(",") || [];
      // 数据加载完成后，设置默认选中的行
      nextTick(() => {
        wristbandList.value.forEach((row) => {
          // console.log('--', row.mac, response.data.connected.includes(row.mac))
          if (response.data.connected.includes(row.mac)) {
            tableRef.value.toggleRowSelection(row, true);
          }
        });
      });
    } else {
      idsWrisband.value = [];
    }
    // console.log("手环列表", idsWrisband.value);
    //  total.value = response.total;
    loadingWrisband.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    mac: undefined,
    class: {
      school: {
        name: undefined,
        id: null,
      },
    },
    topic: undefined,
    version: undefined,
    scene: undefined,
    site: undefined,
    // outdoor: undefined,
    photo: undefined,
  };
  proxy.resetForm("firmwareRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加网关";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getSchoolList().then((res) => {
    schoolList.value = res.data.data.map((school) => {
      return {
        label: school.name,
        value: school.id,
        photo: school.photo,
      };
    });
  });
  const mac = row.mac;
  getGatewayByMac(mac).then(async (response) => {
    form.value = response.data;
    console.log('before', form.value)
    form.value.version = `${form.value.version_bin}/${form.value.version_fs}`;
    if (form.value.class == null) {
      form.value.class = {
        id: null,
        name: null,
        school: {
          name: undefined,
          id: null,
        },
      };
    } else {
      // console.log('form.value.class',form.value.class);
      let params = {
        school_id: form.value.class.school.id,
      };
      await getClassList(params).then((res) => {
        classList.value = res.data.data.map((item) => {
          return {
            label: item.name,
            value: item.id,
            photo: item.photo,
          };
        });
      });
    }
    // console.log("form.value", form.value);
    open.value = true;
    title.value = "修改网关";
  });
}

/** 重置手环列表 */
function resetWristband() {
  // form.value = {
  //   id: undefined,
  //   fileid: undefined,
  //   name: undefined,
  //   version: undefined,
  //   raw: false,
  //   desc: undefined,
  //   path: undefined,
  //   firmware: undefined,
  // };
  // proxy.resetForm("firmwareRef");
}

/** 配置手环操作 */
function handleWristband(row) {
  queryParamsWrisband.value.mac = row.mac;
  idsWrisband.value = [];
  // 获取手环数据
  getWristbandLists();
  resetWristband();
  openWristband.value = true;
  titleWristband.value = "网关绑定手环";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["firmwareRef"].validate((valid) => {
    if (valid) {
      if (form.value.version) {
        form.value.version_bin = form.value.version.split("/")[0];
        form.value.version_fs = form.value.version.split("/")[1];
      } else {
        form.value.version_bin = null;
        form.value.version_fs = null;
      }
      // if(form.value.outdoor != 'true'){
        form.value.class.name = classList.value.find(
          (item) => item.value == form.value.class.id
        ).label;
        form.value.class.photo = classList.value.find(
          (item) => item.value == form.value.class.id
        ).photo;
      // }
      if (form.value.mac != undefined) {
        // console.log(form.value);
        console.log("form", form.value);
        updateGagewayByMac(form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("网关修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("网关修改失败");
          }
        });
      } else {
        console.log("新增");
        // // console.log(form.value);
        // createFirmwares(form.value).then((response) => {
        //   // console.log(response);
        //   const { code, data, msg } = response;
        //   if (code === 200) {
        //     proxy.$modal.msgSuccess("网关新增成功");
        //     open.value = false;
        //     getList();
        //   } else {
        //     proxy.$modal.msgError("网关新增失败");
        //   }
        // });
      }
    }
  });
}

/** 关联提交按钮 */
function submitWristbandForm() {
  if (idsWrisband.value.length < 0) {
    proxy.$modal.msgError("请先选择手环！");
    return;
  }
  const params = {
    gw_mac: queryParamsWrisband.value.mac,
    wb_mac: idsWrisband.value,
  };
  // console.log('绑定手环',JSON.stringify(params))
  createGatewayWristband(params).then((response) => {
    // console.log(response);
    const { code, data, msg } = response;
    if (code === 200) {
      proxy.$modal.msgSuccess("绑定手环成功");
      openWristband.value = false;
      // getList();
    } else {
      proxy.$modal.msgError("绑定手环失败");
    }
  });
}

/** 手环多选框选中数据 */
function handleSelectionWristbandChange(selection) {
  idsWrisband.value = selection.map((item) => item.mac);
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.mac//row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除网关为"' + ids + '"的数据项？')
    .then(function () {
      return deleteGwByMac(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  /*proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);*/
}
function handleOperate(row, type) {
  if(type == 'buzzer'){
    // 蜂鸣器操作
    proxy.$modal.msgError("蜂鸣器操作即将开放");
    return
  }
  if(type == 'telnet'){
    // 生成 32位长度数字+字母的token，用于连接BeConsole
    const token = Math.random().toString(36).substring(2, 34);
    getClassGwControlLed({
      action: "telnet",
      gw_mac: row.mac,
      token: token,
      // url: `wss://beconsole-proxy.zhiyu.school/device?token=${token}`,
    }).then((res) => {
      console.log("等待连接BeConsole res", res);
      proxy.$modal.msgSuccess("连接BeConsole");
      // 打开BeConsole
      window.open(`https://beconsole.become.cool/?connType=ws&connUrl=wss://beconsole-proxy.zhiyu.school/terminal?token=${token}`);
    });
  }
}
function handleLight(row, color) {
  console.log("闪灯 选择", row, color);
  const colorValue = color === 'red' ? {
    red: 1,// 0-255, 0:不亮, 255需转1因为硬件暂不支持
    green: 0,
    blue: 0,
  } : color === 'green' ? {
    red: 0,
    green: 1,
    blue: 0,
  } : color === 'blue' ? {
    red: 0,
    green: 0,
    blue: 1,
  } : {
    red: 1,
    green: 1,
    blue: 1,
  };
  console.log("闪灯 入参 ", {
    action: "led",
    gw_mac: row.mac,
    led1: colorValue});
  getClassGwControlLed({
    action: "led",
    gw_mac: row.mac,
    led1: colorValue,
  }).then((res) => {
    console.log("闪灯 res", res);
    proxy.$modal.msgSuccess("闪灯成功");
  });
}
// 切换教育集团
function changeQueryEdgroup() {
  queryParams.value.school_id = null;
  schoolList.value = [];
  let params = {
    id: queryParams.value.edgroup_id,
  };
  getSchoolList(params).then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}
// 切换学校
function changeQuerySchool() {
  queryParams.value.class_id = null;
  classList.value = [];
  let params = {
    school_id: queryParams.value.school_id,
  };
  // console.log('params', params)
  getClassList(params).then((res) => {
    // console.log("班级列表", res.data.data);
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}

function initData(){
  getEdgroupList().then((res) => {
    EdgroupList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getSchoolList().then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getClassList().then((res) => {
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getList();
}
// function changeOutdoor(val){
//   debugger
//   if(val == 'true'){
//     form.value.class.id = null
//     form.value.class.name = null
//   }
// }
initData()
// 在定义 queryParams 后，将 props 中的值赋给 queryParams
watch(
  () => [props.edgroup_id, props.school_id, props.class_id],
  ([newEdgroup, newSchool, newClass], [oldEdgroup, oldSchool, oldClass] = []) => {
    let needQuery = false;
    if (newEdgroup !== oldEdgroup) {
      queryParams.value.edgroup_id = newEdgroup || null;
      if (newEdgroup) changeQueryEdgroup();
      needQuery = true;
    }
    if (newSchool !== oldSchool) {
      queryParams.value.school_id = newSchool || null;
      if (newSchool) changeQuerySchool();
      needQuery = true;
    }
    if (newClass !== oldClass) {
      queryParams.value.class_id = newClass || null;
      needQuery = true;
    }
    if (needQuery) {
      getList();
    }
  },
  { immediate: true }
);
</script>
